#include "common.h"
#include "globals.h"
#include "logger.h"
#include "shared_func.h"
#include "termlist.h"
#include "idxMerger.h"

//-----globals---------
FILE* g_input;
char* fconf="./conf/merger.ini";
Globs g;
Stats s;
//---------------------

void usage() {
  fprintf(stderr, "\n");
  fprintf(stderr, "Project    : %s\n", PROJECT_NAME);
  fprintf(stderr, "BuildDate  : %s\n", BuildDate);
  fprintf(stderr, "Description: %s\n", DESCRIPTION);
  fprintf(stderr, "Usage: ./merger\n");
  fprintf(stderr, "\n");
}

static int init_config() {
  IniContext iniContext;
  int ret;
  char* cstr;

  if((ret=iniLoadFromFile(fconf, &iniContext)) != 0) {
    FATAL("error load descriptor file:%s",
	fconf);
    return E_RET;
  }

  set_log_level(iniGetStrValue(NULL, "log_level", &iniContext));

  cstr = iniGetStrValue(NULL, "in_data_path", &iniContext);
  if(cstr == NULL) {
    FATAL("error get value : in_data_path");
    return E_RET;
  }
  strcpy(g.in_data_path,
      cstr);

  cstr = iniGetStrValue(NULL, "out_data_path", &iniContext);
  if(cstr == NULL) {
    FATAL("error get value : out_data_path");
    return E_RET;
  }

  g.num_terms_per_file = 
    iniGetIntValue(NULL, "num_terms_per_file", &iniContext, -1);
  if(g.num_terms_per_file == -1) {
    FATAL("error get value : num_terms_per_file");
    return E_RET;
  }

  strcpy(g.out_data_path,
      cstr);

  return S_RET;
}

int init() {
  int ret;
  log_init();
  g_log_context.log_level = LOG_DEBUG;
  memset(&g, 0, sizeof(g));
  memset(&s, 0, sizeof(s));
  
  ret = init_config();
  if(ret != S_RET) {
    FATAL("read config error");
    exit(-1);
  }

  return S_RET;
}

void do_it() {
  IdxMerger* idxm = new IdxMerger();
  assert(idxm);
  int ret;
  char fname[NAME_LEN];
  char ofname[NAME_LEN];

  for(int i = 0 ; i < LEVEL_NUM ; ++i) {
    sprintf(fname, "%s/%s.%d", 
	g.in_data_path,
	INVERT_LIST_NAME, i);
    sprintf(ofname, "%s.%d",
	IDX_FNAME, i);
    ret = idxm->merge(fname, ofname);
    if(ret != S_RET) {
      FATAL("error merge prefix[%s]",
	  fname);
      exit(-1);
    }
  }
}


int main(int argc, char** argv) {
  int ret;

  g_input = stdin;

  ret = init();
  if(ret != S_RET) {
    FATAL("error init system");
    exit(-1);
  }

  if(argc == 2) {
    if(strcmp(argv[1], "-v") == 0 ||
	strcmp(argv[1], "--version") == 0 ||
	strcmp(argv[1], "-h") == 0) {
      usage();
      exit(-1);
    }
    g.mapid = atoi(argv[1]);
  }
  else if(argc == 1) {
    g.mapid = 0;
  }
  else {
    usage();
    exit(-1);
  }
  
  do_it();

  return S_RET;
}
